package com.hmall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.util.ThreadLocalUtil;
import com.hmall.user.mapper.AddressMapper;
import com.hmall.user.mapper.UserMapper;
import com.hmall.user.pojo.Address;
import com.hmall.user.pojo.User;
import com.hmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, com.hmall.user.pojo.User> implements UserService {
    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 从本地线程取出用户Id,查询用户的所有收货地址
     *
     * @return
     */
    @Override
    public List<Address> getAddress() {
        Long userId = ThreadLocalUtil.getUserId();
        LambdaQueryWrapper<Address> lambdaQuery = Wrappers.lambdaQuery(Address.class);
        lambdaQuery.eq(Address::getUserId, userId);
        return addressMapper.selectList(lambdaQuery);
    }

    /**
     * 根据地址Id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public Address queryAddress(Long id) {
        LambdaQueryWrapper<Address> lambdaQuery = Wrappers.lambdaQuery(Address.class);
        lambdaQuery.eq(Address::getId, id);

        return addressMapper.selectOne(lambdaQuery);
    }

    /**
     * 根据用户Id查询用户功能
     *
     * @param userId
     * @return
     */
    @Override
    public User findUser(Long userId) {
        LambdaQueryWrapper<User> lambdaQuery = Wrappers.lambdaQuery(User.class);
        lambdaQuery.eq(User::getId, userId);
        return userMapper.selectOne(lambdaQuery);
    }

    /**
     * 支付扣除余额功能
     *
     * @param userId
     * @param num
     * @return
     */
    @Override
    public Boolean pay(Long userId, Long num) {
        User user = userMapper.selectById(userId);
        LambdaUpdateWrapper<User> lambdaUpdate = Wrappers.lambdaUpdate(User.class);
        Long balance = user.getBalance();
        lambdaUpdate.ge(User::getId, user.getId()).set(User::getBalance, balance - num);
        int updateResult = userMapper.update(null, lambdaUpdate);
        return updateResult > 0;
    }

    /**
     * 查询用户余额
     * @param userId
     * @return
     */
    @Override
    public Long queryBalance(Long userId) {
        User user = userMapper.selectById(userId);
        return user.getBalance();
    }

}
